package com.itlong.cloud.rabbitmq.consumer.elevatorconsumers;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.itlong.cloud.POJO.PO.DeviceBusinessElevatorChangeLogPO;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.commons.service.ICloudElevatorService;
import com.itlong.cloud.commons.service.IPushCloudElevatorChangeLogService;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.enumerate.CloudElevatorChangeBusinessEnum;
import com.itlong.cloud.utils.node.JsonUtil;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <desc>
 *     云电梯同步业务指令消费过程同步业务指令操作队列消费者
 * </desc>
 *
 * @createDate 2018/04/03
 */
@Component
public class CloudElevatorChangeBusinessConsumer03 {

    private static final Logger LOG = LoggerFactory.getLogger(CloudElevatorChangeBusinessConsumer03.class);

    @Autowired
    ICloudElevatorService iCloudElevatorService;

    @Autowired
    IPushCloudElevatorChangeLogService iPushCloudElevatorChangeLogService;


    /**
    * <desc>
    *     云电梯同步业务指令消费过程
    * </desc>
    *
     * @param message 监听到的业务消息
     * @param channel 频道
    * @author cuiduanwu
    * @createDate 2017-11-06
    */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ELEVATOR_CHANGE_BUSINESS_QUEUE)
    public void process(Message message, Channel channel) throws IOException{
        byte[] body = message.getBody();
        try {
            Thread.sleep(700);
            TimeTaskDeadMessageQueuePO timeTaskDeadMessageQueuePO = JsonUtil.toObject(new String(body),
                    TimeTaskDeadMessageQueuePO.class);
            String content = timeTaskDeadMessageQueuePO.getMessageContent();
            JSONObject jsdata = JSONObject.parseObject(content);

            JSONArray jsdataArr = jsdata.getJSONArray("data");
            List<DeviceBusinessElevatorChangeLogPO> changeLogPOS = JSON.parseObject(JSONObject.toJSONString(jsdataArr), new TypeReference<List<DeviceBusinessElevatorChangeLogPO>>() {});
            if (changeLogPOS != null && changeLogPOS.size()>0){
                List<DeviceBusinessElevatorChangeLogPO> removeChangeLogPOS = new ArrayList<>();
                for (DeviceBusinessElevatorChangeLogPO dbclPO:changeLogPOS){
                    if (StringUtils.isBlank(dbclPO.getProjectId())){
                        removeChangeLogPOS.add(dbclPO);
                    }else {
                        JSONArray commandDataArr = null,commandAttacheDataArr = null;
                        JSONObject datajs = new JSONObject();
                        String buildAndUnitId = "";
                        if (dbclPO.getCommandType()== CloudElevatorChangeBusinessEnum.PUSH_ROOM_PWD.getCommandType()){  //房间信息产生变化
                            commandDataArr = JSONArray.parseArray(dbclPO.getCommandParameter());
                        }
                        if (commandDataArr != null&&commandDataArr.size()>0){
                            commandAttacheDataArr = new JSONArray();
                            for (int i=0;i<commandDataArr.size();i++){
                                datajs = commandDataArr.getJSONObject(i);
                                buildAndUnitId = iCloudElevatorService.deviceChangeLogGetBuildAndUnitIdByRoomId(datajs.getString("roomId"));
                                if(StringUtils.isNotBlank(buildAndUnitId)){
                                    datajs.put("buildId",buildAndUnitId.substring(0,buildAndUnitId.indexOf(",")));
                                    datajs.put("unitId",buildAndUnitId.substring(buildAndUnitId.indexOf(",")+1,buildAndUnitId.length()));
                                }
                                commandAttacheDataArr.add(datajs);
                            }
                            dbclPO.setCommandParameter(JSONObject.toJSONString(commandAttacheDataArr));
                        }
                    }
                }
                if (removeChangeLogPOS != null&&removeChangeLogPOS.size()>0){
                    LOG.info("RabbitMQ_云电梯同步业务指令操作队列_异常生产数据:\n"+JSONObject.toJSONString(removeChangeLogPOS));
                    changeLogPOS.removeAll(removeChangeLogPOS);
                }
                if (changeLogPOS.size() > 0) {
                    if (changeLogPOS.get(0).getCommandType() == 1) {//项目信息变更
                        iPushCloudElevatorChangeLogService.setPushProject(changeLogPOS);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 2) {//固定密码信息
                        iPushCloudElevatorChangeLogService.setPushFixedPassword(changeLogPOS);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 3) {//设备信息
                        iPushCloudElevatorChangeLogService.setPushDevice(changeLogPOS);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 4 || changeLogPOS.get(0).getCommandType() == 5) {
                        Integer fullType;
                        if (changeLogPOS.get(0).getCommandType() == 4) {//房间全量更新
                            //房间全量更新 /device/pullDeviceAuthInfo
                            fullType=CloudElevatorChangeBusinessEnum.PUSH_ROOM_FULL.getCommandType();
                        }else {//云电梯业务服务器地址变更
                            //云电梯业务服务器地址变更 /device/login
                            fullType=CloudElevatorChangeBusinessEnum.PUSH_SERVER.getCommandType();
                        }
                        iPushCloudElevatorChangeLogService.updateFull(changeLogPOS.get(0).getProjectId(), fullType,changeLogPOS.get(0).getCommandParameter());
                    }
                    if (changeLogPOS.get(0).getCommandType() == 6) {//设备项目信息变更
                        iPushCloudElevatorChangeLogService.setPushDeviceProjectInfo(changeLogPOS);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 7) {//楼层映射信息
                        iPushCloudElevatorChangeLogService.setPushDeviceFloorInfo(changeLogPOS);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 8) {//用户所在项目信息变更
                        iPushCloudElevatorChangeLogService.setPushUserProject(changeLogPOS, 1);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 9) {//用户的房间信息变更
                        iPushCloudElevatorChangeLogService.setPushUserProject(changeLogPOS, 2);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 11) {//黑名单信息变更
                        iPushCloudElevatorChangeLogService.setBlackList(changeLogPOS);
                    }
                    if(changeLogPOS.get(0).getCommandType() == 10){//用户临时权限变更
                        iPushCloudElevatorChangeLogService.setPushTempAuth(changeLogPOS);
                    }
                }
            }
            //LOG.info("RabbitMQ_云电梯同步业务指令操作队列消费端:"+ content);
        } catch (Exception ex) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            LOG.error("【RabbitMQ_云电梯同步业务指令消费端】:消费异常", ex);
        }
        finally {
            //手动确认消息消费成功。
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
